package com.ruyiadmin.springboot.common.handlers.core;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ruyiadmin.springboot.common.core.system.entities.ActionResult;
import com.ruyiadmin.springboot.common.exceptions.RuYiAdminCustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * RuYiAdmin统一异常处理
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-22
 */
@Slf4j
@ControllerAdvice
public class RuYiAdminGlobalExceptionHandler {

    //region 系统级异常处理

    /**
     * 系统级异常处理
     *
     * @param e 异常信息
     * @return ActionResult
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ActionResult error(Exception e) {
        e.printStackTrace();
        return ActionResult.error();
    }

    //endregion

    //region 自定义异常处理

    /**
     * 自定义异常处理
     *
     * @param e 异常信息
     * @return ActionResult
     */
    @ExceptionHandler(RuYiAdminCustomException.class)
    @ResponseBody
    public ActionResult customError(RuYiAdminCustomException e) {
        return ActionResult.error(e.getMessage());
    }

    //endregion

    //region 自定义异常处理

    /**
     * 自定义异常处理
     *
     * @param e 异常信息
     * @return ActionResult
     */
    @ExceptionHandler(TokenExpiredException.class)
    @ResponseBody
    public ActionResult customError(TokenExpiredException e) {
        e.printStackTrace();
        return ActionResult.unauthorized("unauthorized jwt token expired");
    }

    //endregion

    //region 自定义异常处理

    /**
     * 自定义异常处理
     *
     * @param e 异常信息
     * @return ActionResult
     */
    @ExceptionHandler(BlockException.class)
    @ResponseBody
    public ActionResult customError(BlockException e) {
        e.printStackTrace();
        return ActionResult.tooManyRequests("too many requests,please try again later.");
    }

    //endregion

}
